package com.kfm.tool;


import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.kfm.control.JdbcSelect;
import com.kfm.map.ServerTA;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//链接服务器，请求服务器
public class ServerServlet {
    public static List<ServerTA> getResult() throws Exception {
        String sql = "select * from Serverta";
        return JdbcSelect.selectinfo(new ServerTA(), sql);
    }

    /**
     * 判断链接是否成功，返回响应的状态码
     *
     * @param URL 网址
     * @return
     */
    public static int getResponse(String URL) {
        HttpResponse execute = null;
        try {
            execute = HttpRequest.get(URL).timeout(3000).execute();
        } catch (Exception e) {
        }
        if (execute == null) {
            return 504;
        } else {
            execute.getStatus();
        }
        return execute.getStatus();
    }

    /**
     * 通过ftp上传文件,判断服务器上传功能是否正常
     */
    public static boolean ftp(ServerTA server) throws Exception {
        //获取服务器ip地址
        String url = server.getUrl();
        //获取用户名
        String user = server.getUsername();
        //获取用户密码
        String password = server.getPassword();
        //获取链接对象
        Ftp ftp = new Ftp(url, 21, user, password);
        //设置被动模式
        ftp.setMode(FtpMode.Passive);
        //获取所要传输的文件地址
        List<String> files = ServerFile.getFiles();
        for (String file : files) {
            boolean upload = ftp.upload("/", new File(file));
            JdbcSelect.insertInfoLogs("上传文件：" + file + " " + upload);
            JdbcSelect.close();
        }
        try {
            ftp.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    public static boolean ftp(ServerTA server,String file) throws Exception {
        //获取服务器ip地址
        String url = server.getUrl();
        //获取用户名
        String user = server.getUsername();
        //获取用户密码
        String password = server.getPassword();
        //获取链接对象
        Ftp ftp = new Ftp(url, 21, user, password);
        //设置被动模式
        ftp.setMode(FtpMode.Passive);
        boolean upload = ftp.upload("/", new File(file));
        JdbcSelect.insertInfoLogs("上传文件：" + " " + file + " " + upload);
        JdbcSelect.close();
        try {
            ftp.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
